import log from '../../helpers/logger';

// 权限级别常量
export const PERMISSION_LEVEL = {
  READ: 1,
  WRITE: 2,
  AUTHORIZE: 3
};

/**
 * 轻量化的行级数据权限中间件
 * @param entityType 实体类型
 */
const rowLevelPermission = (entityType: string) => {
  return async (req, res, next) => {
    // 检查是否启用行级数据权限
    const isEnabled = process.env.ROW_LEVEL_PERMISSION_ENABLED === 'true';
    if (!isEnabled) {
      return next();
    }

    // 确保用户已登录
    const userId = res.locals.id?.user;
    if (!userId) {
      return res.status(403).json({ err: 'not login' });
    }

    // 添加权限上下文信息
    res.locals.rowLevelPermission = {
      enabled: true,
      userId,
      entityType
    };

    log.debug(`[ROW_LEVEL_PERMISSION] User ${userId} accessing ${entityType}`);
    return next();
  };
};

export default rowLevelPermission;